package net.homelinux.chaoswg.io.renga.krypto.datatypes.numerical;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeSet;

public class UnsignedNBitFactory {
    private final static Map<Integer, Class<? extends UnsignedNBit>> _mapping = new HashMap<Integer, Class <? extends UnsignedNBit>> ();
    
    private static UnsignedNBitFactory _this;
    
    private UnsignedNBitFactory () {
    }
    
    public boolean exists (final int i) {
        return _mapping.get(i) != null; 
    }
    
    public static UnsignedNBitFactory createUnsignedNBitFactory () {
        if (_this == null) {
            _this = new UnsignedNBitFactory ();
        }
        return _this;
    }
    
    public UnsignedNBit getLargestPossible () {
        return this.get (this.getLargest());        
    }
    
    private int getLargest () {
        return new TreeSet<Integer> (_mapping.keySet()).last();
    }
    
    public void set (final int n, final Class<? extends UnsignedNBit> toCreate) {
        _mapping.put(n, toCreate);
    }
    
    public UnsignedNBit get (final int n) {
        UnsignedNBit toReturn = null;
        
        Class<? extends UnsignedNBit> toCreate = _mapping.get(n);
        
        if (toCreate != null) {
            try {
                toReturn = toCreate.newInstance();
            } catch (IllegalAccessException exp) {
                
            } catch (InstantiationException exp) {
                
            }
        }
        
        return toReturn;        
    }
}
